import 'package:decimal/decimal.dart';
import 'package:get/get.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/utils/common_util/date_util.dart';
import 'package:star_author/utils/common_util/num_util.dart';
import 'package:star_author/utils/config_provider_util.dart';
import 'package:star_author/utils/utils.dart';
import 'package:provider/provider.dart';

class BackflowModel {
  late Map originalData;
  late int id;
  late String originalStatus;
  late String status;
  late String cover;
  late String? hdCover = null;
  late String? expiredAt;
  late Map<String, dynamic> goods;
  late String rejectedReason;
  late String opening_insight;
  late bool is_offline_saling;
  late Map<String, dynamic>? backAddress;
  late String strategy;
  late List price_range;
  late List appraisal_price;
  late String flaw;
  late int tendersCount;
  late int limited;
  late int expired_evaluation_duration;
  late String store_page_description;
  late String anchor_nickname;
  late String tender_page_description;
  late int expired_evaluation_duration_with_count_down;
  late int approvedEvaluationCount;
  late String evaluatedPrice;
  late String recording_video;
  late String title;
  late String previewConfirmedPrice;
  late num moneyForPlatform;
  late num moneyForHitter;
  late String commission;
  late String confirmedPrice;
  late String? normalDiscountPrice;
  late String? immediate_discount_price;
  late String price_range_show_name;
  late bool isImmediate;
  late String category;
  late bool canOnsaleFromClosed;
  late bool select;
  late bool canSelect;
  late Map<String, dynamic>? rating;
  late Map<String, dynamic>? order;
  late String? orderStatus;
  late bool requested_explain;
  late String number;
  late bool immediateSupport;
  late int stock;
  late double previous_max_tender_price;
  late int range_of_requested_queue;
  late int already_tenders_count;
  late int need_tenders_count;
  late Map<String, dynamic>? logistic;
  late Map<String, dynamic>? winning_order;
  late String? storeCode;
  late Map<String, dynamic>? backLogistic;
  late String backCode;
  late String rateForDeducting;
  late String rateForHitter;
  late String rateForTender;
  late String rateForDeductingImmediateCompetitiveStrategy;
  late String backflowReceivedAddress;
  late String backflow_received_address_without_mobile;
  late String? tenderPrice;
  late String? first_evaluation_at;
  late String? evaluated_again_at;
  late String? attach_back_address_at;
  late String? confirmed_at;
  late int userId;
  late List<dynamic>? images;
  late List<dynamic>? videos;
  late List<dynamic>? studios;
  late bool stared;
  late bool can_evaluated_again;
  late bool has_evaluated_again;
  late String can_self_help_evaluated_again_at;
  late bool recyclable;
  late bool first_evaluation;

  late String? price;
  late String? certificate;
  late String? specification;
  late String? processStatus;
  late String? description;
  late String? created_at;
  late String? sent_at;
  late String? updated_at;
  late String? evaluated_at;
  late String? wait_at;
  late String? back_at;
  late String? send_back_at;
  late String? onsale_at;
  late String? finished_at;
  late String condition_stop_time;
  late String? expired_evaluated_at;
  late String? first_evaluated_at;
  late bool? is_special_offer;
  late bool sonance;
  late bool braceletTip;
  late int express_logs_id;
  late dynamic rate_for_guarantee_deducting;
  late bool back_cash_on_delivery;
  late bool newbie;
  late Map user;

  BackflowModel(Map item) {
    this.originalData = item;
    this.id = item['id'];
    this.first_evaluation_at = item['first_evaluation_at'] ?? "";
    this.evaluated_again_at = item['evaluated_again_at'] ?? "";
    this.attach_back_address_at = item['attach_back_address_at'] ?? "";
    this.confirmed_at = item['confirmed_at'] ?? "";
    this.expired_evaluated_at = item['expired_evaluated_at'] ?? "";
    if (item['rate_for_guarantee_deducting'] != null) {
      if (item['rate_for_guarantee_deducting'] is num) {
        this.rate_for_guarantee_deducting =
            item['rate_for_guarantee_deducting'] ?? 0;
      } else if (item['rate_for_guarantee_deducting'] is String) {
        this.rate_for_guarantee_deducting =
            item['rate_for_guarantee_deducting'] ?? "0";
      }
    } else {
      this.rate_for_guarantee_deducting =
          item['rate_for_guarantee_deducting'] ?? "0";
    }
    this.is_special_offer = item['is_special_offer'];
    this.stock = item['stock'];
    this.previous_max_tender_price =
        double.parse((item['previous_max_tender_price'] ?? 0).toString());
    this.originalStatus = item['status'];

    Map<String, dynamic> goods = item['goods'] ?? {};
    Map<String, dynamic> winning_order = item['winning_order'] ?? {};
    var cover = goods['cover'];
    if (cover != null && cover is Map) {
      this.hdCover = cover['url'];
    }
    this.goods = goods;
    this.winning_order = winning_order;
    this.need_tenders_count = item['need_tenders_count'] ?? 0;
    this.already_tenders_count = item['already_tenders_count'] ?? 0;
    this.cover = item['cover'] ?? '';
    this.created_at = item['created_at'] ?? '';
    this.updated_at = item['updated_at'] ?? '';
    this.sent_at = item['sent_at'] ?? '';
    this.send_back_at = item['send_back_at'] ?? '';
    this.evaluated_at = item['evaluated_at'] ?? '';
    this.first_evaluated_at = item['first_evaluated_at'] ?? '';
    this.wait_at = item['wait_at'] ?? '';
    this.back_at = item['back_at'] ?? '';
    this.send_back_at = item['send_back_at'] ?? '';
    this.onsale_at = item['onsale_at'] ?? '';
    this.finished_at = item['finished_at'] ?? '';
    this.condition_stop_time = item['condition_stop_time'] ?? '';
    this.expiredAt = item['expired_at'] ?? '';
    this.rejectedReason = item['rejected_reason'] ?? "";
    this.opening_insight = item['opening_insight'] ?? "";
    this.is_offline_saling = item['is_offline_saling'] ?? false;
    if (item['can_self_help_evaluated_again_at'] != null) {
      this.can_self_help_evaluated_again_at =
          item['can_self_help_evaluated_again_at'] ?? '';
    } else {
      this.can_self_help_evaluated_again_at = "";
    }

    this.backAddress = item['back_address'];
    this.strategy = item['strategy'] ?? "";
    this.flaw = item['flaw'] ?? "";
    this.price_range = item['price_range'] ?? [];
    this.appraisal_price = item['appraisal_price'] ?? [];
    this.store_page_description = item['store_page_description'] ?? "";
    this.anchor_nickname = item['anchor_nickname'] ?? "";
    this.tender_page_description = item['tender_page_description'] ?? "";
    this.tendersCount = item['tenders_count'] ?? 0;
    this.limited = item['limited'] ?? 0;
    this.expired_evaluation_duration =
        item['expired_evaluation_duration'] ?? 44;
    this.expired_evaluation_duration_with_count_down =
        item['expired_evaluation_duration_with_count_down'] ?? 0;
    this.approvedEvaluationCount = item['approved_evaluation_count'] ?? 0;
    this.evaluatedPrice = formatPrice(item['evaluated_price']);
    this.title = goods['title'] ?? '';
    this.recording_video = item['recording_video'] ?? '';
    this.previewConfirmedPrice = formatPrice(item['preview_confirmed_price']);
    this.moneyForPlatform = parseNum(item['money_for_platform']);
    this.moneyForHitter = parseNum(item['money_for_hitter']);
    Decimal _commission = Decimal.parse(this.moneyForHitter.toString()) +
        Decimal.parse(this.moneyForPlatform.toString());
    this.commission = _commission.toString();
    this.confirmedPrice = formatPrice(item['confirmed_price']);
    this.normalDiscountPrice = parseString(item['normal_discount_price']);
    this.immediate_discount_price =
        parseString(item['immediate_discount_price'] ?? "0");
    this.isImmediate = item['is_immediate'] ?? false;
    this.category = this.goods['category'] ?? '';
    this.price_range_show_name = item['price_range_show_name'] ?? '';
    this.canOnsaleFromClosed = item['can_onsale_from_closed'] ?? false;
    this.order = item['order'];
    this.orderStatus = this.order?['status'];
    this.number = item['number'] ?? "";
    this.requested_explain = item['requested_explain'] ?? false;
    this.range_of_requested_queue = item['range_of_requested_queue'] ?? 0;
    this.immediateSupport = item['immediate_support'] ?? false;
    this.logistic = item['logistic'] ?? {};
    this.storeCode = item['store_code'] ?? '';
    this.backLogistic = item['back_logistic'] ?? {};
    this.backCode = item['back_code'] ?? "";
    this.rateForDeducting = item['rate_for_deducting'] ?? "";
    this.rateForHitter = item['rate_for_hitter'] ?? "";
    this.rateForTender = item['rate_for_tender'] ?? "";
    this.rateForDeductingImmediateCompetitiveStrategy = (double.parse(
                item['rate_for_deducting_immediate_competitive_strategy'] ??
                    '0') *
            100)
        .toString();
    this.backflowReceivedAddress = item['backflow_received_address'] ?? "";
    this.backflow_received_address_without_mobile =
        item['backflow_received_address_without_mobile'] ?? "";
    this.tenderPrice = item['tender_price'];
    this.images = item['goods']['images'];
    this.videos = item['goods']['videos'];
    this.studios = item['studios'] ?? [];
    this.stared = item['stared'] ?? false;
    this.recyclable = item['recyclable'] ?? false;
    this.first_evaluation = item['first_evaluation'] ?? false;
    this.rating = item['rating'] ?? {};
    this.can_evaluated_again = item['can_evaluated_again'] ?? false;
    this.price = item['goods']['price'];
    this.certificate = item['goods']['certificate'];
    this.specification = item['goods']['specification'];
    this.processStatus = item['goods']['process_status'];
    this.description = item['goods']['description'];
    this.userId = item['user_id'] ?? 0;
    this.sonance = item['sonance'] ?? false;
    this.express_logs_id = item['express_logs_id'] ?? 0;
    this.braceletTip = item['bracelet_tip'] ?? false;
    this.back_cash_on_delivery = item['back_cash_on_delivery'] ?? false;
    this.newbie = item['newbie'] ?? false;
    this.user = item['user'] ?? {};
    this.has_evaluated_again = item['has_evaluated_again'] ?? false;

    ///需优化
    if (this.originalStatus == 'onsale' && this.stock == 0) {
      //winning_order只有这个中拍订单是得我来付的，这个字段才有值
      // LOGIC: 只有本人的回流单会有winning_order字段，非本人的回流单该字段为null
      if (this.winning_order != null &&
          this.winning_order!["status"] != "initial") {
        this.status = "sold";
      } else {
        this.status = "wait_pay";
      }
    } else {
      this.status = this.originalStatus;
    }
  }

  //是否提前结拍
  bool get isConditionStopTime {
    return condition_stop_time.isNotEmpty;
  }

  //获取市场价
  List get priceRange {
    if (appraisal_price.length == 0 && price_range.length == 0) {
      return [];
    }
    //估价师估价了 使用 估价师的价格
    if ((price_range.length) > 0) {
      return price_range;
    } else {
      return appraisal_price;
    }
  }

  bool isMine(int id) {
    return userId == id;
  }

  //字画
  bool get isPaint {
    return (goods['category_prefix'] ?? "") == "P";
  }

  //待寄出和已寄出显示画家图片数量和跳转判断
  bool get isPaintName {
    return isPaint &&
        [
          "initial",
          "sent",
        ].contains(status);
  }

  //货品已收回
  bool get checkSendingBack {
    return backLogistic!.isNotEmpty &&
        checkNotNullOrNotEmpty(backAddress) &&
        status != 'closed';
  }

  //${App.evaluation_text}价低于500并且第一次
  get canReturn {
    String price = "";
    if (!checkStringNullOrEmpty(immediate_discount_price) &&
        double.parse(immediate_discount_price!) > 0) {
      price = immediate_discount_price!;
    }
    return double.parse(price) < 500 && first_evaluation;
  }

  // bool

  //货品已收回
  bool get isSendingBack {
    return checkNotNullOrNotEmpty(backAddress) && originalStatus != 'closed';
  }

  //是否评论
  bool get isRating {
    return rating!.isEmpty;
  }

  bool get canBack {
    UserProvider userProvider =
        Provider.of<UserProvider>(Get.context!, listen: false);
    return !checkNotNullOrNotEmpty(backAddress) &&
        orderStatus != 'initial' &&
        userProvider.user!['id'] == userId &&
        recyclable &&
        originalStatus != 'closed';
  }

  bool get showInfo {
    return !['initial', 'sent', 'back', 'closed'].contains(this.status) ||
        this.evaluatedPrice.isNotEmpty;
  }

  bool get isCompetitive {
    return strategy == 'competitive_strategy';
  }

  bool get isEvaluation {
    return ['waitconfirm', 'evaluation'].contains(status) ||
        (status == 'back' && checkStringNullOrEmpty(confirmedPrice));
  }

  //已寄出未入库取消回流，后台标记可取回后显示收回货品按钮
  bool get isShowText {
    return !recyclable &&
        (checkNotNullOrNotEmpty(logistic) || checkNotNullOrNotEmpty(storeCode));
  }

  //待回款
  bool get waitMoney {
    return status == "wait_pay";
  }

  //补偿金
  double get compensate {
    double deduct_guarantee_rate_price = NumUtil.multiply(
        double.parse(immediate_discount_price ?? "0"),
        ConfigProviderUtil.deduct_guarantee_rate);

    double result = deduct_guarantee_rate_price;
    if (deduct_guarantee_rate_price > ConfigProviderUtil.max_compensation) {
      result = ConfigProviderUtil.max_compensation.toDouble();
    }

    return result;
  }

  //是上门取货还是快递
  get logisticString {
    String value = "";
    if (!checkStringNullOrEmpty(storeCode)) {
      //显示取货码
      value = "取货码 ${storeCode}";
    } else {
      //快递
      value = "${logistic!['company_name'] ?? ""} ${logistic!['no'] ?? ""}";
    }
    return value;
  }

  //evaluation_end_type
  get evaluation_end_type {
    String value = '';

    Duration? countDownVal =
        DateUtil.getDateTime(formatDate(expired_evaluated_at ?? ''))
            ?.difference(DateTime.now());

    bool isExpired = countDownVal == null || countDownVal.inSeconds < 0;

    bool tender_full = already_tenders_count == need_tenders_count;

    if (has_evaluated_again) {
      value = 'again';
    } else if (isExpired || (!isExpired && !tender_full)) {
      value = 'expired';
    } else if (tender_full) {
      value = 'full';
    }

    return value;
  }

  //黄金回流单
  bool get isGoldBackflow {
    return (goods['category_prefix'] ?? '') == 'G';
  }

  //黄金直播间
  Map? goldLivingDetailMap;

  //直播间状态
  bool? get goldBackflowLivingStatus {
    if (isGoldBackflow &&
        status == 'evaluation' &&
        originalData['studios'] != null &&
        originalData['studios'].length > 0) {
      goldLivingDetailMap = originalData['studios'][0];
      if ((goldLivingDetailMap!['switch'] ?? false) &&
          (originalData['explaining'] ?? false)) {
        //直播间开启中-货品检测中
        return true;
      } else {
        //未开启直播
        //直播间开启中-货品未检测
        return false;
      }
    }
    //不显示直播UI
    return null;
  }

  String get goldLivingBeginTimeText {
    String beginTime = '';
    if (goldLivingDetailMap == null) {
      return '';
    }
    String begin_at = goldLivingDetailMap!['begin_at'] ?? '';
    if (DateUtil.isToday(DateUtil.getDateMsByTimeStr(begin_at))) {
      beginTime =
          '今天 ${DateUtil.formatDateStr(goldLivingDetailMap!['begin_at'] ?? '', format: 'HH:mm')}';
    } else if (DateUtil.isTomorrow(
        DateUtil.getDateTime(begin_at) ?? DateTime.now(), DateTime.now())) {
      beginTime =
          '明天 ${DateUtil.formatDateStr(goldLivingDetailMap!['begin_at'] ?? '', format: 'HH:mm')}';
    } else {
      beginTime = DateUtil.formatDateStr(goldLivingDetailMap!['begin_at'] ?? '',
          format: 'MM月dd日 HH:mm');
    }

    return beginTime;
  }

  // static String get RateForHitter {
  //   return NumUtil.multiply(
  //       Provider.of<ConfigProvider>(Get.context!, listen: false)
  //           .get('settings')['rate_for_hitter'],
  //       100)
  //       .toInt()
  //       .toString() +
  //       "%";

  Map<String, dynamic> toJson(BackflowModel backflowModel) {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = backflowModel.id;
    data['number'] = backflowModel.number;
    data['status'] = backflowModel.status;
    data['immediate_support'] = backflowModel.immediateSupport;
    data['stock'] = backflowModel.stock;
    data['previous_max_tender_price'] = backflowModel.previous_max_tender_price;
    data['created_at'] = backflowModel.created_at;
    data['updated_at'] = backflowModel.updated_at;
    data['evaluated_price'] = backflowModel.evaluatedPrice;
    data['confirmed_price'] = backflowModel.confirmedPrice;
    data['onsale_at'] = backflowModel.onsale_at;
    data['approved_evaluation_count'] = backflowModel.approvedEvaluationCount;
    data['expired_at'] = backflowModel.expiredAt;
    data['user_id'] = backflowModel.userId;
    data['store_code'] = backflowModel.storeCode;
    data['rejected_reason'] = backflowModel.rejectedReason;
    data['opening_insight'] = backflowModel.opening_insight;
    data['finished_at'] = backflowModel.finished_at;
    data['condition_stop_time'] = backflowModel.condition_stop_time;
    data['backflow_received_address'] = backflowModel.backflowReceivedAddress;
    data['backflow_received_address_without_mobile'] =
        backflowModel.backflow_received_address_without_mobile;
    data['immediate_discount_price'] = backflowModel.immediate_discount_price;
    data['normal_discount_price'] = backflowModel.normalDiscountPrice;
    data['limited'] = backflowModel.limited;
    data['expired_evaluation_duration'] =
        backflowModel.expired_evaluation_duration;
    data['expired_evaluation_duration_with_count_down'] =
        backflowModel.expired_evaluation_duration_with_count_down;
    data['strategy'] = backflowModel.strategy;
    data['tenders_count'] = backflowModel.tendersCount;
    data['store_page_description'] = backflowModel.store_page_description;
    data['anchor_nickname'] = backflowModel.anchor_nickname;
    data['tender_page_description'] = backflowModel.tender_page_description;
    data['rate_for_tender'] = backflowModel.rateForTender;
    data['preview_confirmed_price'] = backflowModel.previewConfirmedPrice;
    data['back_code'] = backflowModel.backCode;
    data['rate_for_hitter'] = backflowModel.rateForHitter;
    data['recyclable'] = backflowModel.recyclable;
    data['is_offline_saling'] = backflowModel.is_offline_saling;
    data['expired_evaluated_at'] = backflowModel.expired_evaluated_at;
    data['evaluated_at'] = backflowModel.evaluated_at;
    data['need_tenders_count'] = backflowModel.need_tenders_count;
    data['already_tenders_count'] = backflowModel.already_tenders_count;
    data['rate_for_deducting_immediate_competitive_strategy'] =
        backflowModel.rateForDeductingImmediateCompetitiveStrategy;
    data['send_back_at'] = backflowModel.send_back_at;
    data['back_at'] = backflowModel.back_at;
    data['first_evaluation'] = backflowModel.first_evaluation;
    data['sonance'] = backflowModel.sonance;
    data['express_logs_id'] = backflowModel.express_logs_id;
    data['sent_at'] = backflowModel.sent_at;
    data['wait_at'] = backflowModel.wait_at;
    data['evaluated_again_at'] = backflowModel.evaluated_again_at;
    data['goods'] = backflowModel.goods;
    data['logistic'] = backflowModel.logistic;
    data['back_logistic'] = backflowModel.backLogistic;
    data['back_address'] = backflowModel.backAddress;
    data['rating'] = backflowModel.rating;
    data['price_range_show_name'] = backflowModel.price_range_show_name;
    data['confirmed_at'] = backflowModel.confirmed_at;
    data['attach_back_address_at'] = backflowModel.attach_back_address_at;
    data['first_evaluated_at'] = backflowModel.first_evaluated_at;
    data['flaw'] = backflowModel.flaw;
    data['price_range'] = backflowModel.price_range;
    data['appraisal_price'] = backflowModel.appraisal_price;
    data['rate_for_guarantee_deducting'] =
        backflowModel.rate_for_guarantee_deducting;
    data['is_immediate'] = backflowModel.isImmediate;
    data['is_special_offer'] = backflowModel.is_special_offer;
    data['can_evaluated_again'] = backflowModel.can_evaluated_again;
    data['tender_price'] = backflowModel.tenderPrice;
    data['can_onsale_from_closed'] = backflowModel.canOnsaleFromClosed;
    data['rate_for_deducting'] = backflowModel.rateForDeducting;
    data['money_for_hitter'] = backflowModel.moneyForHitter;
    data['money_for_platform'] = backflowModel.moneyForPlatform;
    data['cover'] = backflowModel.cover;
    data['recording_video'] = backflowModel.recording_video;
    data['winning_order'] = backflowModel.winning_order;
    if (backflowModel.studios != null) {
      data['studios'] = backflowModel.studios;
    }
    data['bracelet_tip'] = backflowModel.braceletTip;
    data['stared'] = backflowModel.stared;
    data['requested_explain'] = backflowModel.requested_explain;
    data['range_of_requested_queue'] = backflowModel.range_of_requested_queue;
    data['back_cash_on_delivery'] = backflowModel.back_cash_on_delivery;
    data['newbie'] = backflowModel.newbie;
    data['user'] = backflowModel.user;
    data['has_evaluated_again'] = backflowModel.has_evaluated_again;
    return data;
  }
}
